package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        // 服务项提交时间
        serviceItem.setCreateTime(new Date());
        // 补充审核状态
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
            // 如果不是套餐：不需要审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_ON_REQUIRED);
        } else {
            // 是套餐：需要审核：
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }
        // 上下架状态： 默认下架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);

        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        // 1、通过id 查询出旧的数据：
        ServiceItem item = serviceItemMapper.selectByPrimaryKey(serviceItem.getId());
        // 在审核中的数据不可以修改
        if (ServiceItem.AUDITSTATUS_AUDITING.equals(item.getAuditStatus())) {
            throw new BusinessException("服务项正在审核，不可以修改。");
        }
        // 在上架的数据不可以修改：
        if (ServiceItem.SALESTATUS_ON.equals(item.getSaleStatus())) {
            throw new BusinessException("服务项上架中，请下架后再修改。");
        }
        // 2、把用户前端表单输入的新数据替换旧数据：
        item.setName(serviceItem.getName());
        item.setOriginalPrice(serviceItem.getOriginalPrice());
        item.setDiscountPrice(serviceItem.getDiscountPrice());
        item.setInfo(serviceItem.getInfo());
        item.setServiceCatalog(serviceItem.getServiceCatalog());
        // 3、更新：
        serviceItemMapper.updateByPrimaryKey(item);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(dictId);
            // 判断服务项是否上架状态：
            if (serviceItem == null || ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())) {
                // 如果是上架的，不能删除：
                throw new BusinessException("该服务项上架状态，不能删除。");
            }
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    // 上架
    @Override
    public void saleOn(Long id) {
        // 判断参数异常
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (serviceItem == null || ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("参数异常");
        }
        // 普通服务项，直接上架：
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
            serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
            return;
        } else {
            // 如果是套餐--要审核通过才可以上架
            if (ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())) {
                serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
                return;
            } else {
                throw new BusinessException("审核未通过，不能上架");
            }
        }
    }

    // 下架
    @Override
    public void saleOff(Long id) {
        // 判断参数异常
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (serviceItem == null || ServiceItem.SALESTATUS_OFF.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("参数异常");
        }
        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_OFF);
    }

    // 发起启动服务项套装审核流程
    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        // 根据服务项id  查询服务项，判断服务项状态为 初始化才可以启动审核
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (serviceItem == null || !ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("只有初始化的服务项才可以发起审核");
        }
        // 1、修改服务项的状态为 审核中：
        serviceItemMapper.changeAuditStatus(id, ServiceItem.AUDITSTATUS_AUDITING);

        // 2、保存审核信息记录表
        CarPackageAudit audit = new CarPackageAudit();
        // 服务项id
        audit.setServiceItemId(id);
        // 服务项备注：
        audit.setServiceItemInfo(serviceItem.getInfo());
        // 服务项审核价格：折扣后的价格
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        // 创建者：
        audit.setCreator(ShiroUtils.getUser().getUserName());
        // 当前审核人ID：店长的id
        audit.setAuditorId(director);
        // 关联流程定义对象的id：bpmn_info 表：
        audit.setBpmnInfoId(bpmnInfoId);
        // 备注：
        audit.setInfo(info);
        // 状态：进行中
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        // 创建时间：
        audit.setCreateTime(new Date());
        // 保存：
        carPackageAuditService.save(audit);

        // 启动流程实例，传入参数
        HashMap<String, Object> map = new HashMap<>();
        if (director != null) {
            // 把店长的id 存入到流程实例的审核的参数中
            map.put("director", director.toString());
        }
        if (finance != null) {
            // 把财务的id 存入流程实例的审核的参数中
            map.put("finance", finance.toString());
        }
        // 保存金额：用于流程实例的分支判断,Activiti 7中的流程实例参数不能存Bigdecime，所以存Long 类型
        map.put("discountPrice", serviceItem.getDiscountPrice().longValue());
        // 在流程定义表中获取流程定义的 key
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        // 启动流程，通过流程定义key，绑定审核信息记录表 业务Businesskey，传入参数
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceByKey(bpmnInfo.getActProcessKey(), audit.getId().toString(), map);

        // 流程实例id（流程实例启动后才有，所以在流程启动实例后再修改到审核信息记录表中）
        audit.setInstanceId(processInstance.getId());
        carPackageAuditService.update(audit);
    }
}
